package com.byteshake.common.base

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Color
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.ContextCompat

abstract class BaseActivity: AppCompatActivity() {

    protected val TAG by lazy { javaClass.simpleName }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStatusBarColor(getBarColor())
        initView(savedInstanceState)
        initData(savedInstanceState)
    }

    abstract fun initView(savedInstanceState: Bundle?)
    abstract fun initData(savedInstanceState: Bundle?)


    open fun getBarColor() : Int{
        return Color.WHITE
    }
    protected open fun setStatusBarColor(statusBarColor: Int) {
        val window = window
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = Color.TRANSPARENT
        window.decorView.systemUiVisibility =
            View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        if (Build.BRAND.equals("XiaoMi", ignoreCase = true)) {
            //状态栏颜色字体(白底黑字)修改 MIUI6+
            setMiuiStatusBarDarkMode(this, true)
        } else if (Build.BRAND.equals("MeiZu", ignoreCase = true)) {
            //状态栏颜色字体(白底黑字)修改 Flyme4+
            setMeizuStatusBarDarkIcon(this, true)
        } else if (isOPPOColorOS3()) {
            setOPPOStausBar(true)
        }
    }

    /**
     * 状态栏颜色字体(白底黑字)修改 MIUI6+
     *
     * @param activity activity
     * @param darkMode darkMode
     */
    private fun setMiuiStatusBarDarkMode(activity: Activity, darkMode: Boolean) {
        if (Build.VERSION.SDK_INT >= 28) {
            return
        }
        try {
            val clazz: Class<out Window?> = activity.window.javaClass
            val darkModeFlag: Int
            @SuppressLint("PrivateApi") val layoutParams =
                Class.forName("android.view.MiuiWindowManager\$LayoutParams")
            val field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE")
            darkModeFlag = field.getInt(layoutParams)
            val extraFlagField = clazz.getMethod(
                "setExtraFlags",
                Int::class.javaPrimitiveType,
                Int::class.javaPrimitiveType
            )
            extraFlagField.invoke(activity.window, if (darkMode) darkModeFlag else 0, darkModeFlag)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 状态栏颜色字体(白底黑字)修改 Flyme4+
     *
     * @param activity activity
     * @param darkMode darkMode
     */
    private fun setMeizuStatusBarDarkIcon(activity: Activity, darkMode: Boolean) {
        try {
            val lp = activity.window.attributes
            val darkFlag = WindowManager.LayoutParams::class.java
                .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON")
            val meizuFlags = WindowManager.LayoutParams::class.java
                .getDeclaredField("meizuFlags")
            darkFlag.isAccessible = true
            meizuFlags.isAccessible = true
            val bit = darkFlag.getInt(null)
            var value = meizuFlags.getInt(lp)
            value = if (darkMode) {
                value or bit
            } else {
                value and bit.inv()
            }
            meizuFlags.setInt(lp, value)
            activity.window.attributes = lp
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    /**
     * 是否ColorOS3.0的OPPO机型
     */
    private fun isOPPOColorOS3(): Boolean {
        return try {
            val cla = Class.forName("android.os.SystemProperties")
            val mtd = cla.getMethod("get", String::class.java)
            var `val` = mtd.invoke(null, "ro.build.version.opporom") as String
            `val` = `val`.replace("[vV]".toRegex(), "")
            if (`val`.length > 0) {
                `val` = `val`.substring(0, 1)
                val version = `val`.toInt()
                return version >= 3
            }
            false
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    /**
     * 对Android5.1版本并且是ColorOS3.0的OPPO机型
     */
    private fun setOPPOStausBar(isDarkText: Boolean) {
        //控制字体颜色，只有黑白两色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
            && Build.VERSION.SDK_INT < Build.VERSION_CODES.M
        ) {
            val SYSTEM_UI_FLAG_OP_STATUS_BAR_TINT = if (isDarkText) 0x00000010 else 0x00190000
            val window = window
            val decorView = window.decorView
            decorView.systemUiVisibility = 0 or SYSTEM_UI_FLAG_OP_STATUS_BAR_TINT
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) //可有可无
            window.statusBarColor = Color.WHITE
        }
    }


    /**
     * 设置页面statusBar高度 内边距
     */
    open fun setStatusBarPadding(viewGroup: ViewGroup) {
        val statusBarHeight = getStatusBarHeight()
        viewGroup.setPadding(viewGroup.paddingLeft,statusBarHeight,viewGroup.paddingRight,viewGroup.paddingBottom)
    }

    /** 设置状态栏高度  外边距 */
    open fun setStatusBarMargin(viewGroup: ViewGroup) {
        val rootViewGroup = viewGroup.parent as ViewGroup
        if (rootViewGroup is FrameLayout) {
            val layoutParams = FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            layoutParams.topMargin = getStatusBarHeight()
            viewGroup.layoutParams = layoutParams
        } else if (rootViewGroup is RelativeLayout) {
            val layoutParams = RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            layoutParams.topMargin = getStatusBarHeight()
            viewGroup.layoutParams = layoutParams
        } else if (rootViewGroup is LinearLayout) {
            val layoutParams = LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            layoutParams.topMargin = getStatusBarHeight()
            viewGroup.layoutParams = layoutParams
        } else if (rootViewGroup is CoordinatorLayout) {
            val layoutParams = FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            layoutParams.topMargin = getStatusBarHeight()
            viewGroup.layoutParams = layoutParams
        }
    }

    @SuppressLint("DiscouragedApi")
    open fun getStatusBarHeight(): Int {
        var result = 0
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            result = resources.getDimensionPixelSize(resourceId)
        }
        return result
    }
}